package com.xiashitech.agent.instrumentation.biz.userinfo.httprequest;

import cn.hutool.core.util.StrUtil;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.constants.SpecialConfigString;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.base.context.TraceContextVars;
import com.xiashitech.agent.instrumentation.httprequest.XSHttpServletRequestWrapper;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.agent.utils.XSUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import ognl.Ognl;
import ognl.OgnlException;

import java.util.HashMap;
import java.util.Map;

public class UserInfoHelper {

    public static void captureUserId(UserRequest userRequest) {
        //新实现的捕获业务ID的逻辑不再去rule.usermatch包绕一圈，那里已经快失控！
        try {
            XSHttpServletRequestWrapper request = (XSHttpServletRequestWrapper)userRequest.getRequest();
            String userId = null;
            String userIdPath = XSUtil.getAgentConfigBySystemId(AgentConfigDTO.getConfig().getUseridpath());
            String realIdPath = StrUtil.subAfter(userIdPath, SpecialConfigString.BIZ_USER_REQUEST.getConfiString(), true);
            if (request.getContentType()!= null && request.getContentType().contains("json")){
                userId = getUserIdFromRequestBody(request, realIdPath);
            }
            if (XSUtil.isEmpty(userId)){
                userId = getUserIdFromRequestAttribute(request, realIdPath);
            }
            userRequest.setUserid(userId);
            TraceContextVars.get().set("xs.userId",userRequest.getUserid() == null ? "" : userRequest.getUserid());
        }catch (Throwable throwable){
            StartConfig.throwableStackPrinter(throwable);
        }
    }

    private static String getUserIdFromRequestAttribute(XSHttpServletRequestWrapper request, String realIdPath){
        String userId = null;
        Map<String,String> realIdMap = JsonUtil.convertStringToObject(realIdPath.replaceAll("'", "\""), HashMap.class);
        String userIdPath = realIdMap == null ? null : realIdMap.get("url");
        userId = request.getParameter(userIdPath);
        if (XSUtil.isEmpty(userId)){
            userId = String.valueOf(request.getAttribute(userIdPath) == null ? null : request.getAttribute(userIdPath));
        }
        return userId;
    }

    private static String getUserIdFromRequestBody(XSHttpServletRequestWrapper request, String realIdPath) throws OgnlException {
        String userId = null;
        String requestBodyJson = new String(request.getBody());
        if (XSUtil.isNotEmpty(requestBodyJson)){
            Map<String,String> realIdMap = JsonUtil.convertStringToObject(realIdPath.replaceAll("'", "\""), HashMap.class);
            String userIdPath = realIdMap == null ? null : realIdMap.get("body");
            Map<String,Object> requestBodyMap =  JsonUtil.convertStringToObject(requestBodyJson, HashMap.class);
            if (XSUtil.isNotEmpty(realIdPath)){
                userId = String.valueOf(Ognl.getValue(userIdPath, requestBodyMap));
            }
        }
        return userId;
    }

}
